﻿using System;
using System.IO;
using System.Collections.Generic;

public interface ILogger
{
    void Log(string message);
}


public class ConsoleLogger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine($"ConsoleLogger: {message}");
    }
}

public class FileLogger : ILogger
{
    private readonly string _fileName;

    public FileLogger(string fileName)
    {
        _fileName = fileName;
    }

    public void Log(string message)
    {
        File.AppendAllText(_fileName, $"FileLogger: {message}\n");
    }
}

public class DatabaseLogger : ILogger
{
    public void Log(string message)
    {
        // 假设我们将日志插入到数据库，简单打印模拟
        Console.WriteLine($"DatabaseLogger (mock insert): {message}");
    }
}
public class LoggerFactory
{
    public static ILogger CreateLogger(string loggerType, string fileName = "app.log")
    {
        switch (loggerType.ToLower())
        {
            case "console":
                return new ConsoleLogger();
            case "file":
                return new FileLogger(fileName);
            case "database":
                return new DatabaseLogger();
            default:
                throw new ArgumentException("Unknown logger type");
        }
    }
}
public class TimestampLoggerDecorator : ILogger
{
    private readonly ILogger _logger;

    public TimestampLoggerDecorator(ILogger logger)
    {
        _logger = logger;
    }

    public void Log(string message)
    {
        string timestampedMessage = $"{DateTime.Now} - {message}";
        _logger.Log(timestampedMessage);
    }
}


public class LogSubject
{
    private readonly List<ILogger> _observers = new List<ILogger>();

    public void AddLogger(ILogger logger)
    {
        _observers.Add(logger);
    }

    public void RemoveLogger(ILogger logger)
    {
        _observers.Remove(logger);
    }

    public void NotifyLoggers(string message)
    {
        foreach (var observer in _observers)
        {
            observer.Log(message);
        }
    }
}
public class Program
{
    public static void Main()
    {
        // 创建日志主体
        LogSubject logSystem = new LogSubject();

        // 使用工厂创建不同类型的日志记录器
        ILogger consoleLogger = LoggerFactory.CreateLogger("console");
        ILogger fileLogger = LoggerFactory.CreateLogger("file", "application.log");
        ILogger databaseLogger = LoggerFactory.CreateLogger("database");

        // 为控制台日志记录器添加时间戳功能
        ILogger timestampedConsoleLogger = new TimestampLoggerDecorator(consoleLogger);

        // 添加日志记录器到日志主体
        logSystem.AddLogger(timestampedConsoleLogger);
        logSystem.AddLogger(fileLogger);
        logSystem.AddLogger(databaseLogger);

        // 记录日志
        logSystem.NotifyLoggers("This is a test log message.");
    }
}
